YAHOO.namespace("pingmob");
YAHOO.namespace("pingmob.container");

YAHOO.util.Event.onDOMReady(function() {
	YAHOO.pingmob.listSalesTerminal = function() {
		
		var number_per_page_default = 10;
		var Dom = YAHOO.util.Dom,
			Event = YAHOO.util.Event;
		
		var myPaginator = new YAHOO.widget.Paginator({
            containers : ['salesterminal-paging', 'salesterminal-paging_top'],
            rowsPerPage : number_per_page_default,
            firstPageLinkLabel : messages['label.first.page'],
            previousPageLinkLabel : messages['label.pre.page'],
            nextPageLinkLabel : messages['label.next.page'],
            lastPageLinkLabel : messages['label.last.page'],            
            previousPageLinkClass : "yui-pg-previous gc-inbox-prev",
            nextPageLinkClass : "yui-pg-next gc-inbox-next"
        });
		
        var myTableConfig = {
            paginator : myPaginator,
            MSG_EMPTY : messages["js.no.records.found"],
            dynamicData : true,
            initialLoad : false,
            width:'100%'
        };
        
        var formatBoolean = function(elCell, oRecord, oColumn, oData) {
            if(oData === true) {
                elCell.innerHTML = "是";
            }
			if(oData === false){
                elCell.innerHTML = "否";
            }			
		};
		
		var formatEdit = function(elCell, oRecord, oColumn, oData) {
			if(oData === true) {
				elCell.innerHTML = '<img src="/static/images/edit.gif" title="编辑" />';
				elCell.style.cursor = 'pointer';						
			} else {
				elCell.innerHTML = "";
			}		
		}

		var myColumnDefs = [
			{key : "id", label : "序号", sortable : true},
			{key : "province", label : "省份", sortable : false},
			{key : "city", label : "城市", sortable : false},
			{key : "district", label : "市辖区/县级市/县", sortable : false},
			{key : "terminalName", label : "终端名称", sortable : false},
			{key : "terminalTypeName", label : "终端类型", sortable : false},
			{key : "terminalLevel", label : "终端级别", sortable : false},
			{key : "isCoreTerminal", label : "是核心终端", sortable : false, formatter : formatBoolean},
			{key : "terminalAddress", label : "终端地址", sortable : false},
			{key : "channelModeName", label : "渠道模式", sortable : false},
			{key : "salesYear", label : "销售年度", sortable : false},
			{key : "salesAmount", label : "销售额（万元）", sortable : false},
			{key : "isCompositeTerminal", label : "是复合终端", sortable : false, formatter : formatBoolean},
			{key : "compositeWithName", label : "复合品牌", sortable : false},
			{key : "terminalPositionName", label : "终端位置", sortable : false},
			{key : "terminalLayoutName", label : "店面布局", sortable : false},
			{key : "areaSizeName", label : "当前面积", sortable : false},
			{key : "ozingBarCountName", label : "柜台数量", sortable : false},
			{key : "hasBackground", label : "有背景", sortable : false, formatter : formatBoolean},
			{key : "storeManager", label : "店长", sortable : false},
			{key : "terminalPhone", label : "电话", sortable : false},
            {key : "canEdit", label : "操作", className:"table-action", action:'edit', formatter : formatEdit}			
		];
		
		var myDataSource = new YAHOO.util.DataSource('/agent/salesterminal/json?');
		myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.responseSchema = {
            resultsList : 'records',
            metaFields : {
                totalRecords : 'totalRecords',
                paginationRecordOffset : "startIndex",
                paginationRowsPerPage : "pageSize",
                sortKey : "sort",
                sortDir : "dir"
            }
        };

		var myDataTable = new YAHOO.widget.DataTable("salesterminal-list", myColumnDefs, myDataSource, myTableConfig);

		// Show loading message while page is being rendered
		myDataTable.showTableMessage(myDataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);
		
		// Add the instances to the YAHOO.example namespace for inspection
        YAHOO.pingmob.BHMIntegration_files = {
            myPaginator  : myPaginator,
            myDataSource : myDataSource,
            myDataTable  : myDataTable
        };
		
        // Integrate with Browser History Manager
        var History = YAHOO.util.History;

        // Define a custom function to route sorting through the Browser History Manager
        var handleSorting = function (oColumn) {
            // Calculate next sort direction for given Column
            var sDir = this.getColumnSortDir(oColumn);

            // The next state will reflect the new sort values
            // while preserving existing pagination rows-per-page
            // As a best practice, a new sort will reset to page 0
            var newState = generateRequest(0, oColumn.key, sDir, this.get("paginator").getRowsPerPage());

            // Pass the state along to the Browser History Manager
            History.navigate("myTable", newState);
        };
		myDataTable.sortColumn = handleSorting;

        // Define a custom function to route pagination through the Browser History Manager
        var handlePagination = function (state) {
            // The next state will reflect the new pagination values
            // while preserving existing sort values
            // Note that the sort direction needs to be converted from DataTable format to server value
            var sortedBy  = this.get("sortedBy"),
                newState = generateRequest(state.recordOffset, sortedBy.key, sortedBy.dir, state.rowsPerPage);

            // Pass the state along to the Browser History Manager
            History.navigate("myTable", newState);
        };

        // First we must unhook the built-in mechanism...
        myPaginator.unsubscribe("changeRequest", myDataTable.onPaginatorChangeRequest);
        // ...then we hook up our custom function
        myPaginator.subscribe("changeRequest", handlePagination, myDataTable, true);

        // Update totalRecords on the fly with values from server
        myDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
            var meta = oResponse.meta;
            oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
            oPayload.pagination = {
                rowsPerPage : meta.paginationRowsPerPage || number_per_page_default,
                recordOffset : meta.paginationRecordOffset || 0
            };
            if(oPayload.totalRecords == undefined) {
                oPayload.totalRecords = 0;
            }
            oPayload.sortedBy = {
                key : meta.sortKey || "id",
                dir : (meta.sortDir) ? "yui-dt-" + meta.sortDir : "yui-dt-asc" // Convert from server value to DataTable format
            };
            return true;
        };

		var generateRequest	= function(startIndex, sortKey, dir, results) {
			var province = encodeURIComponent(Dom.get("province").value);
			var city = encodeURIComponent(Dom.get("city").value);
			var terminalName = encodeURIComponent(Dom.get("terminalName").value);
			var terminalAddress = encodeURIComponent(Dom.get("terminalAddress").value);
			var salesYear = encodeURIComponent(Dom.get("salesYear").value);			
			
            startIndex = startIndex || 0;
            sortKey = sortKey || "id";
            dir = (dir) ? dir.substring(7) : "desc"; // Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
            results = results || number_per_page_default;

			var urlParameter = "sort=" + sortKey + "&dir=" + dir + "&start_index=" + startIndex + "&num_per_page=" + results;
			urlParameter += "&province=" + province + "&city=" + city + "&terminalName=" + terminalName + "&terminalAddress=" + terminalAddress + "&salesYear=" + salesYear;
			return urlParameter;
		}

        // Called by Browser History Manager to trigger a new state
        var handleHistoryNavigation = function(request) {
            //show the "loading" message.
            myDataTable.getTbodyEl().style.display = "none";
            myDataTable.showTableMessage(messages["js.loading"]);

            // Sends a new request to the DataSource
            myDataSource.sendRequest(request, {
                success : function() {
                    myDataTable.getTbodyEl().style.display = "";
                    myDataTable.hideTableMessage();
                    myDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                failure : function() {
                    myDataTable.getTbodyEl().style.display = "";
                    myDataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                    myDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                scope : myDataTable,
                argument : {} // Pass in container for population at runtime via doBeforeLoadData
            });
        };

        // Calculate the first request
        var initialRequest = History.getBookmarkedState("myTable") || generateRequest(); // Get default values

        // Register the module
        History.register("myTable", initialRequest, handleHistoryNavigation);

        // Render the first view
        History.onReady(function () {
            // Current state after BHM is initialized is the source of truth for what state to render
			renderPage();
        });	

        var renderPage = function () {
            var currentState = History.getCurrentState("myTable");
            handleHistoryNavigation(currentState);
        };

        var searchPage = function () {
            var currentState =  generateRequest();
            handleHistoryNavigation(currentState);
        };

        // Initialize the Browser History Manager.
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		
        var addNewRecord = function (p_oEvent) {
            window.location.href = "/agent/salesterminal/saveorupdate/?action=add";
        };
		
        var refreshList = function (p_oEvent) {
            renderPage();
        };		
		
        myDataTable.subscribe('cellClickEvent', function (ev) {
            var target = YAHOO.util.Event.getTarget(ev);
            var column = this.getColumn(target);
            var record = this.getRecord(target);
            if (column.action == 'edit') {
                window.location.href = '/agent/salesterminal/saveorupdate/?action=edit&id=' + record.getData("id");
            }
        });
		
		var addNewRecord_btn = new YAHOO.widget.Button("addNewRecord", {onclick : {fn : addNewRecord}});
		var refreshList_btn = new YAHOO.widget.Button("refreshList", {onclick : {fn : refreshList}});
		var query_btn = new YAHOO.widget.Button("query_txs_btn", {onclick : {fn : searchPage}});

        return {
            ds:usersDataSource,
            dt:usersDataTable
        };		
		
	}();
});